package com.tools.handler.analysis;

import com.tools.common.result.Result;
import com.tools.handler.StepHandler;
import com.tools.pojo.test.AnalysisResult;
import com.tools.pojo.test.RuleMatchResult;
import com.tools.pojo.workflow.bo.StepContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class ResultPrintStepHandler implements StepHandler {

    private static final String STEP_CODE = "RESULT_PRINT";

    @Override
    public String getStepCode() {
        return STEP_CODE;
    }

    @Override
    public Result<?> execute(StepContext context) {
        try {
            log.info("开始执行结果打印步骤，流程实例ID: {}", context.getFlowInstanceId());

            // 获取分析结果
            AnalysisResult analysisResult = context.getContextData("analysisResult", AnalysisResult.class);
            if (analysisResult == null) {
                return Result.fail("未找到分析结果");
            }

            // 打印分析结果
            printAnalysisResult(analysisResult);

            log.info("结果打印步骤执行成功");
            return Result.success("分析结果打印完成", analysisResult);

        } catch (Exception e) {
            log.error("结果打印步骤执行失败", e);
            return Result.fail("结果打印失败: " + e.getMessage());
        }
    }

    private void printAnalysisResult(AnalysisResult result) {
        System.out.println("\n" + "=".repeat(80));
        System.out.println("                    数据分析结果报告");
        System.out.println("=".repeat(80));

        // 基本信息
        System.out.printf("分析状态: %s\n", result.isSuccess() ? "成功" : "失败");
        System.out.printf("处理消息: %s\n", result.getMessage());
        System.out.printf("处理时间: %d ms\n", result.getProcessingTime());
        System.out.printf("总记录数: %d\n", result.getTotalRecords());
        System.out.printf("匹配记录数: %d\n", result.getMatchedRecords());
        System.out.printf("匹配率: %.2f%%\n",
                (double) result.getMatchedRecords() / result.getTotalRecords() * 100);

        // 规则匹配详情
        System.out.println("\n规则匹配详情:");
        System.out.println("-".repeat(80));
        System.out.printf("%-4s %-20s %-15s %-10s %-15s %-10s %s\n",
                "ID", "规则名称", "字段", "操作符", "期望值", "匹配", "实际值");
        System.out.println("-".repeat(80));

        for (RuleMatchResult match : result.getMatchResults()) {
            System.out.printf("%-4d %-20s %-15s %-10s %-15s %-10s %s\n",
                    match.getRuleId(),
                    truncate(match.getRuleName(), 18),
                    truncate(match.getField(), 13),
                    match.getOperation(),
                    truncate(String.valueOf(match.getExpectedValue()), 13),
                    match.isMatched() ? "✓" : "✗",
                    truncate(String.valueOf(match.getActualValue()), 13));
        }

        // 统计摘要
        System.out.println("\n统计摘要:");
        System.out.println("-".repeat(80));
        Map<String, Object> summary = result.getSummary();
        summary.forEach((key, value) -> System.out.printf("%-20s: %s\n", key, value));

        System.out.println("=".repeat(80));

        // 同时记录到日志
        log.info("数据分析完成: 总规则数={}, 匹配规则数={}, 处理时间={}ms",
                result.getTotalRules(), result.getMatchedRules(), result.getProcessingTime());
    }

    private String truncate(String str, int length) {
        if (str == null) return "";
        return str.length() > length ? str.substring(0, length - 3) + "..." : str;
    }

}
